package graphiceditor4robot.more.actions;

import graphiceditor4robot.more.fsm.FSMChecker;

import org.eclipse.core.resources.IFile;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PlatformUI;

import behaviourdiagram.Behaviour;

public class CheckFSM implements IWorkbenchWindowActionDelegate {

	private Behaviour behaviour;

	public CheckFSM() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void run(IAction action) {
		if (behaviour == null)
			return;
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

		if (page == null)
			return;

		IEditorInput input = page.getActiveEditor().getEditorInput();
		if (!(input instanceof IFileEditorInput)) 
			return;
		
		IFile eclipseFile = ((IFileEditorInput)input).getFile();
		FSMChecker checker = new FSMChecker(behaviour, eclipseFile);
		checker.check();
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection == null){
			return;
		}
		if (selection instanceof IStructuredSelection) {
			IStructuredSelection sel = (IStructuredSelection)selection;
			Object obj = sel.getFirstElement();
			if (obj instanceof IGraphicalEditPart) {
				EObject o = ((IGraphicalEditPart)obj).getNotationView().getElement();
				if (o instanceof Behaviour) {
					behaviour = (Behaviour)o;
				}
			}
		}
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(IWorkbenchWindow window) {
		// TODO Auto-generated method stub

	}

}
